﻿using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wt.wine.Application.Common.Interfaces;
using wt.wine.Domain.Enums;
using wt.wine.Domain.Options;
using System.Net.Http.Json;

namespace wt.wine.Infrastructure.InternalHttp
{
    public class InternalHttpService : IInternalHttpService
    {
        private readonly HttpClient _httpClient;
        private readonly InternalHttpOption _option;
        public InternalHttpService(HttpClient httpClient, IOptions<InternalHttpOption> options)
        {
            _httpClient = httpClient;
            _option = options.Value;
            _httpClient.Timeout = TimeSpan.FromSeconds(3000);
            _httpClient.DefaultRequestHeaders.Add("AppCode", _option.AppCode);

        }
        public async Task<TResponse> PostJsonAsync<TResponse>(ApiServiceType serviceType, string url, object request, CancellationToken cancellationToken)
        {
            try
            {
                var response = await _httpClient.PostAsJsonAsync(GetUrl(serviceType) + url, request, cancellationToken);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception(response.StatusCode.ToString() + "服务端异常");
                }
                var jsonString = await response.Content.ReadAsStringAsync(cancellationToken);
                return JsonConvert.DeserializeObject<TResponse>(jsonString);

                //string json = "{}";
                //return JsonConvert.DeserializeObject<TResponse>(json);
            }
            catch (Exception)
            {

                throw;
            }

        }

        public async Task<TResponse> GetAsync<TResponse>(ApiServiceType serviceType, string url, CancellationToken cancellationToken, Dictionary<string, string> values = null)
        {
            var response = await _httpClient.GetAsync(GetUrl(serviceType) + url, cancellationToken);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(response.StatusCode.ToString() + "服务端异常");
            }
            var jsonString = await response.Content.ReadAsStringAsync(cancellationToken);
            return JsonConvert.DeserializeObject<TResponse>(jsonString);
        }

        private void SetBaseAddress(ApiServiceType serviceType)
        {
            switch (serviceType)
            {
                case ApiServiceType.JiuJi:
                    _httpClient.BaseAddress = new Uri(_option.WtServerUri);
                    break;
            }
        }

        private string GetUrl(ApiServiceType serviceType)
        {
            switch (serviceType)
            {
                case ApiServiceType.JiuJi:
                    return _option.WtServerUri;
            }
            return string.Empty;
        }
    }
}
